<template>
	<!-- <view class="publish-container" :style="{background:t('color2')}"> -->
	<view class="publish-container" >
		<view class="tab-header">
			<view v-for="(tab, index) in all" :key="index" class="all-tab-item" :class="{ active: allTab == index }"
				@tap="Tab(index)">
				{{ tab }}
				<view :style="{ backgroundColor: t('color1') }" class="active-curve"></view>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<view class="content">
			<!-- 图片/视频上传区域 -->
			<view class="upload-section">
				<!-- 图片模式 -->
				<view class="image-list" v-if="allTab == 0">
					<view class="image-item" v-for="(image, index) in imageList" :key="index">
						<image :src="image" mode="aspectFill"></image>
						<view class="delete-btn" @tap.stop="deleteImage(index)">×</view>
					</view>
					<view class="upload-btn" @tap="chooseImage" v-if="imageList && imageList.length<10">
						<text class="plus">+</text>
					</view>
				</view>

				<!-- 视频模式 -->
				<view class="video-upload" v-if="allTab == 1">

					<view class="upload-btn" @tap="chooseVideo" v-if="!video_url.url">
						<text class="plus">+</text>
						<text class="upload-text">上传视频</text>
					</view>
					<view class="video-preview" v-else>
						<video :src="video_url.url" controls></video>
						<view class="delete-btn" @tap.stop="deleteVideo">×</view>
					</view>
				</view>
			</view>

			<!-- 添加标题输入框 -->
			<view class="input-section">
				<input class="title-input" v-model="title" placeholder="添加标题" placeholder-style="color: #999999;" />
			</view>

			<!-- 添加正文输入框 -->
			<view class="input-section">
				<textarea class="content-input" v-model="content" placeholder="添加正文" placeholder-style="color: #999999;"
					maxlength="500" />
				<view class="setting-tag-box">
					<view class="setting-tag" v-for="(item,index) in selectedFriends" :key="index">
						{{item.member.nickname}}
						<text class="remove-tag" @tap="removeFriend(index)">×</text>
					</view>
					<view class="setting-tag add-friend" @tap="showFriendList">
						<text>@好友</text>
					</view>
				</view>
			</view>

			<!-- 底部设置区域 -->
			<view class="bottom-section">
				<view class="setting-item">
					<view class="setting-item-box">
						<image class="setting-item-icon"
							src="https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250418/d79b39ccc0b7a6afa8cfb3504a1d8c23.png"
							mode=""></image>
						<text class="setting-label">推广赚佣</text>
					</view>
					<view class="setting-item-box" @click="toSelection">
						<image v-if="selectedProduct.id" :src="selectedProduct.pic" mode="aspectFill"
							class="product-thumb"></image>
						<text v-else>去选品</text>
						<image class="setting-item-right" src="/static/img/arrowright.png" mode=""></image>
					</view>
				</view>
				<view class="setting-item" @click="openTimeFilter">
					<view class="setting-item-box">
						<image class="setting-item-icon"
							src="https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250408/6e9ac55a57ac2589a9bc178694cf6a04.png"
							mode=""></image>
						<text class="setting-label">{{ timeFilterText }}</text>
					</view>
					<view class="setting-item-box">
						<image class="setting-item-right" src="/static/img/arrowright.png" mode=""></image>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部发布按钮 -->
		<view class="bottom">
			<view class="publish-btn" :class="{ 'can-publish': canPublish }" @tap="publish">
				发布笔记
			</view>
		</view>

		<!-- 可见性选择弹窗 -->
		<view v-if="timeFilterShow" class="popup__container">
			<view class="popup__overlay" @tap.stop="closeTimeFilter"></view>
			<view class="popup__modal">
				<view class="popup__title">
					<view @tap.stop="closeTimeFilter">取消</view>
					<view @tap.stop="confirmTimeFilter">确定</view>
				</view>
				<view class="service-item" v-for="(item, index) in timeFilterOptions" :key="index"
					:style="activeTimeFilterIndex === index ? 'color:' + t('color2') : ''"
					@tap.stop="setActiveTimeFilter(index)">
					{{ item.text }}
				</view>
			</view>
		</view>

		<!-- 好友列表弹框 -->
		<view v-if="friendListShow" class="popup__container">
			<view class="popup__overlay" @tap.stop="closeFriendList"></view>
			<view class="popup__modal friend-list-modal">
				<view class="popup__title">
					<view @tap.stop="closeFriendList">取消</view>
					<view @tap.stop="confirmFriendSelection">确定</view>
				</view>
				<view class="friend-list" v-if="friendList.length>0">
					<view class="friend-item" v-for="(friend, index) in friendList" :key="index"
						@tap="toggleFriendSelection(friend)">
						<image class="friend-avatar" :src="friend.member && friend.member.headimg" mode="aspectFill">
						</image>
						<view class="friend-info">
							<text class="friend-name">{{friend.member&& friend.member.nickname}}</text>
							<text class="friend-status" v-if="friend.is_each_follow === 1">互相关注</text>
						</view>
						<view class="friend-checkbox" :class="{ 'checked': isFriendSelected(friend) }">
							<text v-if="isFriendSelected(friend)">✓</text>
						</view>
					</view>
				</view>
				<view class="load-more" v-else>
					<text>暂无数据</text>
				</view>
				<view class="load-more" v-if="!friendListNoMore">
					<text @tap="loadMoreFriends">加载更多</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var app = getApp();
	export default {
		data() {
			return {
				imageList: [],
				allTab: 0,
				all: ['图片', '视频'],
				title: '',
				content: '',
				isPublic: true,
				timeFilterShow: false,
				timeFilterOptions: [{
						text: '公开可见',
						value: 1
					},
					{
						text: '仅互关好友可见',
						value: 2
					},
					{
						text: '仅自己可见',
						value: 3
					}
				],
				activeTimeFilterIndex: 0,
				timeFilterText: '公开可见',
				timestatus: 1,
				tags: [{
					name: '@好友'
				}],
				opt: {},
				selectedProduct: {
					id: '',
					pic: ''
				},
				video_url: {}, // 视频URL
				videoTempPath: '', // 视频临时路径
				videoThumbnail: '', // 视频封面图
				uploading: false, // 上传状态
				friendListShow: false,
				friendList: [],
				selectedFriends: [],
				friendListPage: 1,
				friendListLimit: 10,
				friendListLoading: false,
				friendListNoMore: false,
				tempSelectedFriends: [], // 临时存储选中的好友
			}
		},
		computed: {
			canPublish() {
				if (this.allTab == 0) { // 图片模式
					return this.imageList.length > 0 && (this.title || this.content);
				} else { // 视频模式
					return this.video_url && (this.title || this.content);
				}
			}
		},
		// 返回时恢复数据（在 onShow 中处理）
		onShow() {
			if (app.globalData.draftData) {
				Object.assign(this.$data, app.globalData.draftData);
				app.globalData.draftData = null; // 清除缓存
			}
		},
		onLoad(opt) {
			this.opt = app.getopts(opt);

			if (this.opt.id && this.opt.pic) {
				this.selectedProduct = {
					id: this.opt.id,
					pic: this.opt.pic
				};
			}
		},
		methods: {
			goBack() {
				uni.navigateBack()
			},
			closeTimeFilter() {
				this.timeFilterShow = false;
			},
			openTimeFilter() {
				this.timeFilterShow = true;
			},
			Tab(index) {
				this.allTab = index;
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
			},
			confirmTimeFilter() {
				const selectedOption = this.timeFilterOptions[this.activeTimeFilterIndex];
				this.timeFilterText = selectedOption.text;
				this.timestatus = selectedOption.value;
				this.timeFilterShow = false;
			},
			setActiveTimeFilter(index) {
				this.activeTimeFilterIndex = index;
			},
			chooseImage() {
				var that = this;

				// 调用选择图片的方法
				app.chooseImage(function(urls) {

					// 遍历选中的图片地址
					for (var i = 0; i < urls.length; i++) {

						// 将图片地址添加到 imageList 数组中
						that.imageList.push(urls[i]);
					}
				}, 9); // 1表示一次只允许选择1张图片
			},
			deleteImage(index) {
				this.imageList.splice(index, 1)
			},
			// 选择视频
			chooseVideo() {
				app.chooseAlbumVideo((urls) => {
					if (urls && urls.length > 0) {
						this.video_url = urls[0]; // 只取第一个视频
						this.videoTempPath = urls[0]; // 保存临时路径
						console.log(this.video_url, "视频");
					}
				}, 1); // 限制只能选择1个视频
			},

			// 删除视频
			deleteVideo() {
				this.video_url = '';
				this.videoTempPath = '';
				this.videoThumbnail = '';
			},
			togglePublic(e) {
				this.isPublic = e.detail.value
			},
			// 发布内容
			publish() {
			  // 1. 检查是否可以发布
			  if (!this.canPublish || this.uploading) return;
			
			  // 2. 校验输入内容
			  if (this.allTab == 0 && this.imageList.length === 0) {
			    uni.showToast({
			      title: '请至少选择一张图片',
			      icon: 'none'
			    });
			    return;
			  }
			
			  if (this.allTab == 1 && !this.video_url) {
			    uni.showToast({
			      title: '请选择一个视频',
			      icon: 'none'
			    });
			    return;
			  }
			
			  if (!this.title && !this.content) {
			    uni.showToast({
			      title: '请输入标题或内容',
			      icon: 'none'
			    });
			    return;
			  }
			
			  // 3. 开始上传
			  this.uploading = true;
			  uni.showLoading({
			    title: '发布中...',
			    mask: true
			  });
			
			  const type = this.allTab === 0 ? 1 : 2; // 1图片 2视频
			  const uploadData = {
			    content: this.content,
			    title: this.title,
			    type: type,
			    visibility: this.timestatus,
			    proids: this.selectedProduct.id || '',
			    friend_mids: this.selectedFriends.map(f => f.member.id).join(',')
			  };
			
			  // 4. 区分图片/视频上传
			  if (type === 1) {
			    uploadData.images = this.imageList.join(',');
			  } else {
			    uploadData.video_url = this.video_url.url;
			  }
			
			  // 5. 调用API
			  app.post('MemberNote/noteAdd', uploadData, (res) => {
			    this.uploadComplete(res);
			  }).catch((err) => {
			    this.handleUploadError(err); // 捕获网络错误
			  });
			},
			
			// 上传完成处理
			uploadComplete(res) {
			  uni.hideLoading();
			  this.uploading = false;
			
			  if (res.status == 200) {
			    // 成功处理
			    uni.showToast({
			      title: '发布成功',
			      icon: 'success'
			    });
			    			
			    // 1.5秒后跳转
			    setTimeout(() => {
			      uni.redirectTo({
			        url: '/pagesEchart/find/index'
			      });
			    }, 1500);
			  }else{
				  // 服务器返回失败
				  uni.showToast({
				    title: `发布失败：${res.msg || '未知错误'}`,
				    icon: 'none',
				    duration: 3000
				  });
				  return; // 不跳转页面
			  }
		
			},
			
			// 处理上传错误（网络问题等）
			handleUploadError(err) {
			  uni.hideLoading();
			  this.uploading = false;
			
			  uni.showToast({
			    title: `发布失败：${err.errMsg || '网络错误'}`,
			    icon: 'none',
			    duration: 3000
			  });
			
			  console.error('发布失败:', err);
			},
			toSelection() {
				app.globalData.draftData = {
					allTab: this.allTab,
					title: this.title,
					content: this.content,
					imageList: this.imageList,
					video_url: this.video_url,
					selectedFriends: this.selectedFriends
				};
				uni.navigateTo({
					url: '/pagesZone/gift/gift_zone?type=1'
				});
			},
			// 显示好友列表
			showFriendList() {

				this.tempSelectedFriends = [...this.selectedFriends]; // 复制当前选中的好友

				this.loadFriends();
			},

			// 关闭好友列表
			closeFriendList() {
				this.friendListShow = false;
				this.tempSelectedFriends = []; // 清空临时选中
			},

			// 确认好友选择
			confirmFriendSelection() {
				this.selectedFriends = [...this.tempSelectedFriends];
				this.friendListShow = false;
			},

			// 加载好友列表
			loadFriends(isLoadMore = false) {
				if (this.friendListLoading || (isLoadMore && this.friendListNoMore)) return;

				this.friendListLoading = true;
				const page = isLoadMore ? this.friendListPage + 1 : 1;

				app.get('MemberNote/followList', {
					page: page,
					limit: this.friendListLimit,
					is_each_follow: 1
				}, (res) => {
					this.friendListLoading = false;

					if (res.status === 200) {
						if (isLoadMore) {
							this.friendList = [...this.friendList, ...res.data];
							this.friendListPage = page;
						} else {
							this.friendList = res.data;
							this.friendListPage = 1;
						}

						this.friendListNoMore = res.data.length < this.friendListLimit;
						this.friendListShow = true;
					} else {
						app.error(res.msg);
					}
				});
			},

			// 加载更多好友
			loadMoreFriends() {
				this.loadFriends(true);
			},

			// 切换好友选择状态
			toggleFriendSelection(friend) {
				const index = this.tempSelectedFriends.findIndex(f => f.id === friend.id);
				if (index > -1) {
					this.tempSelectedFriends.splice(index, 1);
				} else {
					if (this.tempSelectedFriends.length >= 20) {
						uni.showToast({
							title: '最多只能@20个好友',
							icon: 'none'
						});
						return;
					}
					this.tempSelectedFriends.push(friend);
				}
			},

			// 检查好友是否被选中
			isFriendSelected(friend) {
				return this.tempSelectedFriends.some(f => f.id === friend.id);
			},

			// 移除已选好友
			removeFriend(index) {
				this.selectedFriends.splice(index, 1);
			},
		}
	}
</script>
<style lang="scss" scoped>
	.publish-container {
		min-height: 100vh;
		// background-color: #f0f8f8;
		padding-bottom: 120rpx;
	}

	.tab-header {
		display: flex;
		height: 90rpx;
		padding: 20rpx;
		gap: 20rpx;
		align-items: center;
		width: 100vw;
		z-index: 9;
	}

	.all-tab-item {
		text-align: center;
		font-size: 38rpx;
		position: relative;
	}

	.all-tab-item.active {
		font-size: 38rpx;
		font-weight: bold;
		color: #000;
		position: relative;
	}

	.all-tab-item.active .active-curve {
		content: '';
		position: absolute;
		bottom: -12rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
	}

	.content {
		padding: 20rpx;
	}

	/* 上传区域样式 */
	.upload-section {
		margin-bottom: 20rpx;
	}

	/* 图片上传样式 */
	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;

		.image-item {
			width: 152rpx;
			height: 152rpx;
			position: relative;

			image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}

			.delete-btn {
				position: absolute;
				right: -10rpx;
				top: -10rpx;
				width: 40rpx;
				height: 40rpx;
				background: rgba(0, 0, 0, 0.5);
				color: #fff;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
			}
		}

		.upload-btn {
			width: 152rpx;
			height: 152rpx;
			background: #fff;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.plus {
				font-size: 60rpx;
				color: #999;
			}
		}
	}

	/* 视频上传样式 */
	.video-upload {
		width: 100%;

		.video-preview {
			position: relative;
			width: 100%;
			height: 400rpx;
			border-radius: 12rpx;
			overflow: hidden;
			background: #000;

			video {
				width: 100%;
				height: 100%;
			}

			.delete-btn {
				position: absolute;
				right: 10rpx;
				top: 10rpx;
				width: 40rpx;
				height: 40rpx;
				background: rgba(0, 0, 0, 0.5);
				color: #fff;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				z-index: 2;
			}
		}

		.upload-btn {
			width: 100%;
			height: 400rpx;
			background: #fff;
			border-radius: 12rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.plus {
				font-size: 80rpx;
				color: #999;
				margin-bottom: 20rpx;
			}

			.upload-text {
				font-size: 28rpx;
				color: #999;
			}
		}
	}

	/* 输入区域样式 */
	.input-section {
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		background: #fff;

		.title-input {
			font-size: 32rpx;
			height: 80rpx;
			width: 100%;
		}

		.content-input {
			font-size: 28rpx;
			width: 100%;
			height: 200rpx;
		}
	}

	.setting-tag-box {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-top: 20rpx;
	}



	/* 底部设置区域样式 */
	.bottom-section {
		border-radius: 12rpx;


		.setting-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 20rpx;
			border-top: 1rpx solid #f5f5f5;
			background: #fff;
			margin-bottom: 20rpx;
			.setting-item-box {
				display: flex;
				align-items: center;
			}

			.setting-item-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}

			.setting-item-right {
				width: 40rpx;
				height: 40rpx;
			}

			&:last-child {
				border-top: none;
			}

			.setting-label {
				font-size: 28rpx;
				color: #333;
			}

			.product-thumb {
				width: 60rpx;
				height: 60rpx;
				border-radius: 8rpx;
				margin-right: 10rpx;
			}
		}
	}

	/* 底部发布按钮样式 */
	.bottom {
		position: fixed;
		width: calc(100% - 40rpx);
		bottom: 0;
		left: 20rpx;
		right: 20rpx;
		display: flex;
		align-items: center;
		gap: 30rpx;
		padding: 20rpx 0;

	}

	.bottom-left {
		flex-shrink: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.bottom-left-box {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		border-radius: 50%;
		margin-bottom: 10rpx;
	}

	.bottom-left-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.publish-btn {
		flex-grow: 1;
		padding: 20rpx;
		background-color: rgba(255, 253, 248, 1);
		font-weight: 700;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		border-radius: 50rpx;

		&.can-publish {
			background: #07c160;
			color: #fff;
		}
	}

	/* 弹窗样式 */
	.popup__container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
	}

	.popup__overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
	}

	.popup__modal {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.popup__title {
		padding: 30rpx;
		position: relative;
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #eee;
		// margin-bottom: 60rpx;
	}

	.service-item {
		padding: 30rpx 0;
		text-align: center;
		border-bottom: 1px solid #eee;
	}

	.friend-list-modal {
		max-height: 80vh;
		display: flex;
		flex-direction: column;
	}

	.friend-list {
		flex: 1;
		overflow-y: auto;
		padding: 0 30rpx;
	}

	.friend-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1px solid #f5f5f5;
	}

	.friend-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.friend-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.friend-name {
		font-size: 28rpx;
		color: #333;
	}

	.friend-status {
		font-size: 24rpx;
		color: #999;
		margin-top: 4rpx;
	}

	.friend-checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #ddd;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;

		&.checked {
			background-color: #07c160;
			border-color: #07c160;
			color: #fff;
		}
	}

	.load-more {
		text-align: center;
		padding: 20rpx 0;
		color: #666;
		font-size: 28rpx;
	}

	.setting-tag {
		position: relative;
		background-color: #f5f5f5;
		border-radius: 50rpx;
		padding: 10rpx 40rpx 10rpx 20rpx;
		font-size: 24rpx;
		.remove-tag {
			position: absolute;
			right: 10rpx;
			top: 50%;
			transform: translateY(-50%);
			font-size: 24rpx;
			color: #999;
		}
	}

	.add-friend {
		background-color: #f5f5f5;
	}
</style>